package edu.nju.desserthouse.servlets;

import java.io.IOException;

import javax.ejb.EJB;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import nju.edu.desserthouse.model.Clerk;
import edu.nju.desserthouse.dao.ClerkDao;
/**
 * Servlet implementation class ClerkRegisterServvlet
 */
@WebServlet("/register.technician")
public class ClerkRegisterServlet extends HttpServlet {
	
	private static final long serialVersionUID = 1L;
    
	@EJB
	ClerkDao clerkDao;
	
    /**
     * @see HttpServlet#HttpServlet()
     */
    public ClerkRegisterServlet() {
        super();
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8");
		processRequest(request,response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8");
		processRequest (request, response);
	}
	
	public void processRequest(HttpServletRequest req,HttpServletResponse resp) throws ServletException, IOException {
		String to = "/technician/register.jsp";
		RequestDispatcher dispatcher =req.getRequestDispatcher(to);
		
		String message = "";
		
		String account;
		String password;
		String retype;
		String name;
		int position = 0;
		int belong = 0;
		
		try{
			position = Integer.valueOf(req.getParameter("position"));
			belong = Integer.valueOf(req.getParameter("shopno"));
		}catch(Exception e){
			e.printStackTrace();
		}
		
		account = req.getParameter("account");
		password = req.getParameter("password");
		retype = req.getParameter("retype");
		name = req.getParameter("name");
		
		if(account.equals("")||password.equals("")||retype.equals("")||name.equals("")||!(password.equals(retype))){
			message+="You should fill all the blanks correctly!<br>";
			return;
		}
		
		Clerk clerk = new Clerk();
		clerk.setIdByDate();
		clerk.setAccount(account);
		clerk.setPassword(password);
		clerk.setPrivilege(position);
		clerk.setBelong(belong);
		clerk.setName(name);
		
		try{
			clerkDao.save(clerk);
		}catch(Exception e){
			e.printStackTrace();
		}
		
		resp.sendRedirect("/desserthouseWEB/technician/registerSuccess.jsp");
	}

}
